<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/6/19
 * Time: 14:25
 */

namespace iBrand\Shop\Backend\Http\Controllers;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use iBrand\Component\Goods\Models\Season;
use iBrand\Component\Purchase\Repositories\TakeStockItemRepository;
use iBrand\Shop\Backend\Model\TakeStockPlan;
use iBrand\Shop\Backend\Repository\O2oGoodsProductsRepository;
use iBrand\Shop\Backend\Service\CommonService;
use iBrand\Shop\Core\Models\O2oGoodsProducts;
use iBrand\Shop\Core\Models\TakeStockPlanItems;
use Illuminate\Http\Request;

class TakeStockPlanController extends Controller
{
    protected $commonService;
    protected $o2oGoodsProductRepository;
    protected $takeStockItemRepository;
    protected $cache;

    public function __construct(CommonService $commonService,
                                O2oGoodsProductsRepository $o2oGoodsProductsRepository,
                                TakeStockItemRepository $takeStockItemRepository)
    {
        $this->commonService = $commonService;
        $this->o2oGoodsProductRepository = $o2oGoodsProductsRepository;
        $this->takeStockItemRepository = $takeStockItemRepository;
        $this->cache=cache();
    }

    /**
     * 盘点计划列表
     * @return Content
     */
    public function index()
    {
        $lists = TakeStockPlan::where('shop_id',session('shop_id'))->orderBy('created_at', 'desc')->paginate(10);

        return Admin::content(function (Content $content) use ($lists) {
            $content->header('库存盘点计划');
            $content->breadcrumb(
                ['text' => '库存盘点计划', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '库存盘点']
            );

            return $content->body(view('shop-backend::takeStockPlan.index', compact('lists')));
        });
    }

    /**
     * 创建盘点计划
     * @return Content
     */
    public function create()
    {
        $seasons = Season::all();
        $years = $this->commonService->getYearList();

        return Admin::content(function (Content $content) use ($seasons, $years) {
            $content->description('库存盘点计划创建');

            $content->breadcrumb(
                ['text' => '库存盘点计划创建', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '库存盘点']
            );

            return $content->body(view('shop-backend::takeStockPlan.create', compact('seasons', 'years')));
        });
    }

    /**
     * 保存盘点计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $data = $request->except('_token');
        $data['shop_id'] = session('shop_id');
        TakeStockPlan::create($data);
        return $this->ajaxJson();
    }


    /**
     * 创建盘点计划的商品
     * @return \Illuminate\Http\JsonResponse
     */
    public function storeItems()
    {
        $page = request('page') ? request('page') : 1;

        $plan = TakeStockPlan::find(\request('plan_id'));
        $condition = $plan->condition;
        $where['shop_id'] = session('shop_id');

        $products = $this->o2oGoodsProductRepository->getGoodsProductsPaginate($where, [], ['baseGoods'], 20, $condition);
        $lastPage = $products->lastPage();

        if ($products->count()) {
            foreach ($products as $product) {
                $data = [
                    'base_product_id' => $product->product_id,
                    'shop_product_id' => $product->id,
                    'quantity' => $product->store_nums
                ];

                if (TakeStockPlanItems::where('take_stock_plan_id', $plan->id)->where('base_product_id', $product->product_id)->first()) {
                    continue;
                }

                $plan->items()->create($data);
            }
        }

        if ($page == $lastPage) {
            return $this->ajaxJson(true, ['status' => 'complete']);
        }

        $url_bit = route('admin.shop.take.stock.plan.storeItems', array_merge(['page' => $page + 1], request()->except('page', 'limit')));

        return $this->ajaxJson(true, ['status' => 'goon', 'url' => $url_bit, 'current_page' => $page, 'totalPage' => $lastPage]);

    }

    public function storeItemsModal()
    {
        $store_url = route('admin.shop.take.stock.plan.storeItems', ['plan_id' => \request('plan_id')]);
        return view('shop-backend::takeStockPlan.items_modal', compact('store_url'));
    }

    /**
     * 作废盘点计划\标记为已盘点
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeStatus()
    {
        $plan = TakeStockPlan::find(\request('plan_id'));
        if ($plan) {
            $plan->status = \request('type') == 'cancel' ? 2 : 1;
            $plan->save();
            return $this->ajaxJson();
        }
        return $this->ajaxJson(false, '操作失败');

    }

    /**
     * 查看盘点数据
     * @param $id
     * @return Content
     */
    public function show($id)
    {
        $plan = TakeStockPlan::where(['id' => $id, 'shop_id' => session('shop_id')])->first();
        $take_ids = $plan->takeStocks->pluck('id')->toArray();

        $where['take_stock_id'] = $take_ids;
        $lists = $this->takeStockItemRepository->getTakeStockItemsPaginate($where);

        return Admin::content(function (Content $content) use ($plan, $lists) {
            $content->header('查看盘点数据');
            $content->breadcrumb(
                ['text' => '查看盘点数据', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '库存盘点']
            );

            return $content->body(view('shop-backend::takeStockPlan.show', compact('plan', 'lists')));
        });
    }

    public function getExportData()
    {
        $id=\request('plan_id');
        $page = request('page') ? request('page') : 1;
        $limit = request('limit') ? request('limit') : 40;

        $plan = TakeStockPlan::where(['id' => $id, 'shop_id' => session('shop_id')])->first();
        $take_ids = $plan->takeStocks->pluck('id')->toArray();

        $where['take_stock_id'] = $take_ids;
        $goods = $this->takeStockItemRepository->getTakeStockItemsExcel($where,$limit);

        $lastPage = $goods['lastPage'];
        $goods = $goods['products'];
        $type = request('type');

        if ($page == 1) {
            session(['export_take_item_goods_cache' => generate_export_cache_name('export_take_item_goods_cache_')]);
        }
        $cacheName = session('export_take_item_goods_cache');

        if ($this->cache->has($cacheName)) {
            $cacheData = $this->cache->get($cacheName);
            $this->cache->put($cacheName, array_merge($cacheData, $goods), 300);
        } else {
            $this->cache->put($cacheName, $goods, 300);
        }

        if ($page == $lastPage) {
            $title = ['商品名称', '商品编号', 'SKU', '颜色', '尺码','吊牌价', '盘点数量'];

            return $this->ajaxJson(true, ['status' => 'done', 'url' => '', 'type' => $type, 'title' => $title, 'cache' => $cacheName, 'prefix' => 'take_data_']);
        } else {
            $url_bit = route('admin.shop.take.stock.plan.getExportData', array_merge(['page' => $page + 1, 'limit' => $limit], request()->except('page', 'limit')));

            return $this->ajaxJson(true, ['status' => 'goon', 'url' => $url_bit, 'page' => $page, 'totalPage' => $lastPage]);
        }
    }


}